package com.phonetools.commonutils.security

import java.security.GeneralSecurityException
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

/**
算法:AES
模式:EBC、CBC、PCBC、CTR、CTS、CFB、CFB8~128、OFB、OFB8~128
填充:NoPadding、PKCS5Padding、PKCS7Padding、ISO10126Padding
例:AES/CBC/PKCS7Padding
 * */

/*
fun main() {
    val content = "58 74 6A 2E CB 39 5F BA E5 B9 CD 6D 11 D4 AF 00".hexToByteArray()
    val key = "".md5()
    val iv = "x9z9pXXcbbe2lDL9HHkTRg==".base64Decode()

    try {
        val encrypt = aesEncrypt("AES/CBC/PKCS7Padding", content, key, iv)
        Log.d(TAG, mode + ": " + encrypt.toHex())
        val decrypt = aesDecrypt("AES/CBC/PKCS7Padding", encrypt, key, iv)
        Log.d(TAG, mode + ": " + decrypt.toHex())
    } catch (e: Exception) {
        e.printStackTrace()
    }
}*/

/**
 * AES加密，
 * @param mode 算法/模式/填充
 * @param content 待加密内容
 * @param aesKey key
 * @param iv iv
 * @return ByteArray
 * */
@Throws(GeneralSecurityException::class)
fun aesEncrypt(mode: String, content: ByteArray, aesKey: ByteArray, iv: ByteArray): ByteArray {
    try {
        val cipher = Cipher.getInstance(mode)
        val keySpec = SecretKeySpec(aesKey, "AES")
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, IvParameterSpec(iv))
        return cipher.doFinal(content)
    } catch (e: Exception) {
        throw GeneralSecurityException(e)
    }
}

/**
 * AES解密，
 * @param mode 算法/模式/填充
 * @param content 待加密内容
 * @param aesKey key
 * @param iv iv
 * @return ByteArray
 * */
@Throws(GeneralSecurityException::class)
fun aesDecrypt(mode: String, content: ByteArray, aesKey: ByteArray, iv: ByteArray): ByteArray {
    try {
        val cipher = Cipher.getInstance(mode)
        val sKeySpec = SecretKeySpec(aesKey, "AES")
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec, IvParameterSpec(iv))
        return cipher.doFinal(content)
    } catch (e: Exception) {
        throw GeneralSecurityException(e)
    }
}

